import React, { useState, useEffect } from 'react';
import { AppConfig, AIProvider, MultiAIConfig } from '../types';
import { LocalStorageService } from '../services/LocalStorageService';
import { testDeepSeekAPI, validateDeepSeekAPIKey } from '../utils/testDeepSeekAPI';
import { EnhancedAIService } from '../services/EnhancedAIService';
import { MultiAIConfigForm } from './MultiAIConfigForm';

interface ConfigFormProps {
  config: AppConfig;
  onSave: (config: AppConfig) => Promise<void>;
  saving: boolean;
}

export const ConfigForm: React.FC<ConfigFormProps> = ({
  config,
  onSave,
  saving
}) => {
  const [formData, setFormData] = useState<AppConfig>(config);
  const [excludePatternsText, setExcludePatternsText] = useState('');
  const [currentApiKey, setCurrentApiKey] = useState('');
  const [testingApiKey, setTestingApiKey] = useState(false);
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
  const [activeTab, setActiveTab] = useState<'single' | 'multi'>('single');

  useEffect(() => {
    setFormData(config);
    setExcludePatternsText((config.excludePatterns || []).join('\n'));
    setCurrentApiKey((config.apiKeys && config.apiKeys[config.aiProvider]) || '');
  }, [config]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const updatedConfig = {
      ...formData,
      excludePatterns: excludePatternsText
        .split('\n')
        .map(pattern => pattern.trim())
        .filter(pattern => pattern.length > 0)
    };
    
    await onSave(updatedConfig);
  };

  const handleInputChange = (field: keyof AppConfig, value: string) => {
    if (field === 'aiProvider') {
      const newProvider = value as AIProvider;
      setFormData(prev => ({
        ...prev,
        [field]: newProvider
      }));
      setCurrentApiKey((formData.apiKeys && formData.apiKeys[newProvider]) || '');
    } else {
      setFormData(prev => ({
        ...prev,
        [field]: value
      }));
    }
  };

  const handleApiKeyChange = (value: string) => {
    setCurrentApiKey(value);
    setFormData(prev => ({
      ...prev,
      apiKeys: {
        ...prev.apiKeys,
        [prev.aiProvider]: value
      } as Record<AIProvider, string>
    }));
  };

  const handleMultiAIConfigChange = (multiConfig: MultiAIConfig) => {
    setFormData(prev => ({
      ...prev,
      multiAIConfig: multiConfig
    }));
  };

  const getDefaultMultiAIConfig = (): MultiAIConfig => {
    return {
      models: [
        {
          provider: 'tongyi',
          apiKey: formData.apiKeys?.tongyi || '',
          model: 'qwen-plus',
          temperature: 0.7,
          maxTokens: 2000,
          priority: 1,
          enabled: true,
          maxRetries: 3
        },
        {
          provider: 'tongyi',
          apiKey: formData.apiKeys?.tongyi || '',
          model: 'qwen-turbo',
          temperature: 0.7,
          maxTokens: 2000,
          priority: 2,
          enabled: true,
          maxRetries: 3
        }
      ],
      autoSwitch: true,
      fallbackOnError: true,
      fallbackOnQuotaExhausted: true
    };
  };



  const getProviderDisplayName = (provider: AIProvider): string => {
    switch (provider) {
      case 'google':
        return 'Google AI (Gemini)';
      case 'deepseek':
        return 'DeepSeek';
      case 'tongyi':
        return '通义千问 (Qwen)';
      case 'doubao':
        return '豆包 (Doubao)';
      case 'wenxin':
        return '文心一言 (ERNIE)';
      default:
        return provider;
    }
  };



  const handleTestApiKey = async () => {
    if (!currentApiKey.trim()) {
      setTestResult({ success: false, message: '请先输入API密钥' });
      return;
    }

    setTestingApiKey(true);
    setTestResult(null);

    try {
      const aiService = new EnhancedAIService();
      const testConfig = {
        ...formData,
        apiKeys: {
          ...formData.apiKeys,
          [formData.aiProvider]: currentApiKey
        }
      };
      
      const result = await aiService.testConnection(formData.aiProvider, currentApiKey);
      
      if (result.success) {
        setTestResult({ success: true, message: 'API密钥测试成功！' });
      } else {
        setTestResult({ success: false, message: result.error || 'API密钥测试失败' });
      }
    } catch (error) {
      setTestResult({ 
        success: false, 
        message: error instanceof Error ? error.message : 'API密钥测试失败' 
      });
    } finally {
      setTestingApiKey(false);
    }
  };

  return (
    <div className="bg-white rounded-2xl shadow-strong border border-neutral-200 overflow-hidden animate-fade-in">
      <div className="bg-gradient-to-r from-primary-50 to-secondary-50 px-4 py-4 border-b border-neutral-200">
        <div className="flex items-center space-x-3">
          <div className="w-10 h-10 bg-gradient-to-br from-primary-100 to-secondary-100 rounded-xl flex items-center justify-center shadow-medium">
            <svg className="w-5 h-5 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          </div>
          <div>
            <h2 className="text-lg font-semibold text-neutral-900">系统配置</h2>
            <p className="text-neutral-600 mt-1 text-sm">
              配置您的Git用户信息和AI服务提供商
            </p>
          </div>
        </div>
      </div>
      
      <form onSubmit={handleSubmit} className="p-4 space-y-4">
        {/* Git用户名 */}
        <div>
          <label htmlFor="gitUsername" className="block text-sm font-semibold text-neutral-900 mb-2">
            <span className="flex items-center space-x-2">
              <svg className="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
              <span>Git用户名</span>
            </span>
          </label>
          <input
            type="text"
            id="gitUsername"
            value={formData.gitUsername}
            onChange={(e) => handleInputChange('gitUsername', e.target.value)}
            className="w-full px-3 py-2 border border-neutral-200 rounded-xl shadow-medium focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 hover:shadow-strong text-sm font-medium bg-white"
            placeholder="请输入您的Git用户名"
            required
          />
          <p className="text-xs text-neutral-600 mt-2 flex items-center space-x-2">
            <svg className="w-3 h-3 text-info-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>用于识别您的代码提交记录</span>
          </p>
        </div>

        {/* AI配置选项卡 */}
        <div>
          <div className="flex items-center space-x-2 mb-4">
            <svg className="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
            </svg>
            <span className="text-sm font-semibold text-neutral-900">AI配置</span>
          </div>
          
          {/* 选项卡导航 */}
          <div className="flex space-x-1 bg-gray-100 p-1 rounded-lg mb-4">
            <button
              type="button"
              onClick={() => setActiveTab('single')}
              className={`flex-1 px-3 py-2 text-sm font-medium rounded-md transition-all duration-200 ${
                activeTab === 'single'
                  ? 'bg-white text-blue-600 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              单一AI配置
            </button>
            <button
              type="button"
              onClick={() => setActiveTab('multi')}
              className={`flex-1 px-3 py-2 text-sm font-medium rounded-md transition-all duration-200 ${
                activeTab === 'multi'
                  ? 'bg-white text-blue-600 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              多AI配置
            </button>
          </div>
          
          {/* 选项卡内容 */}
          {activeTab === 'single' ? (
            <div className="space-y-4">
              {/* AI服务提供商 */}
              <div>
                <label htmlFor="aiProvider" className="block text-sm font-medium text-gray-700 mb-2">
                  AI服务提供商
                </label>
                <select
                  id="aiProvider"
                  value={formData.aiProvider}
                  onChange={(e) => handleInputChange('aiProvider', e.target.value as AIProvider)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="tongyi">通义千问 (Qwen)</option>
                  <option value="doubao">豆包 (Doubao)</option>
                </select>
                <p className="text-xs text-gray-600 mt-1">
                  选择用于生成报告的AI服务
                </p>
              </div>

              {/* API密钥 */}
              <div>
          <label htmlFor="apiKey" className="block text-sm font-semibold text-neutral-900 mb-2">
            <span className="flex items-center space-x-2">
              <svg className="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1721 9z" />
              </svg>
              <span>API密钥</span>
            </span>
          </label>
          <div className="flex space-x-2">
            <input
              type="password"
              id="apiKey"
              value={currentApiKey}
              onChange={(e) => {
                handleApiKeyChange(e.target.value);
                setTestResult(null);
              }}
              className="flex-1 px-3 py-2 border border-neutral-200 rounded-xl shadow-medium focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 hover:shadow-strong text-sm font-medium bg-white"
              placeholder={`请输入${getProviderDisplayName(formData.aiProvider)}的API密钥`}
            />
            <button
              type="button"
              onClick={handleTestApiKey}
              disabled={testingApiKey || !currentApiKey.trim()}
              className="px-3 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl hover:from-blue-700 hover:to-blue-800 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:ring-offset-1 disabled:from-neutral-300 disabled:to-neutral-400 disabled:text-neutral-700 disabled:cursor-not-allowed flex items-center space-x-2 transition-all duration-300 font-semibold shadow-strong hover:shadow-stronger transform hover:scale-105 text-sm"
            >
              {testingApiKey && (
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
              )}
              <span>{testingApiKey ? '测试中...' : '测试连接'}</span>
            </button>
          </div>
          {testResult && (
            <div className={`mt-3 p-3 rounded-xl border shadow-medium animate-slide-up ${
              testResult.success 
                ? 'bg-gradient-to-r from-success-50 to-success-100 text-success-800 border-success-200'
                : 'bg-gradient-to-r from-danger-50 to-danger-100 text-danger-800 border-danger-200'
            }`}>
              <div className="flex items-center space-x-2">
                {testResult.success ? (
                  <svg className="w-4 h-4 text-success-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                ) : (
                  <svg className="w-4 h-4 text-danger-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                )}
                <span className="font-semibold text-sm">{testResult.message}</span>
              </div>
            </div>
          )}
          <p className="text-xs text-neutral-600 mt-2 flex items-center space-x-2">
            <svg className="w-3 h-3 text-info-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>请输入您的API密钥以使用AI服务生成报告</span>
          </p>
        </div>
             </div>
           ) : (
             <div>
               <MultiAIConfigForm
                 config={formData.multiAIConfig || getDefaultMultiAIConfig()}
                 onChange={handleMultiAIConfigChange}
                 availableApiKeys={formData.apiKeys || {} as Record<AIProvider, string>}
               />
             </div>
           )}
         </div>

        {/* 排除文件模式 */}
        <div>
          <label htmlFor="excludePatterns" className="block text-sm font-semibold text-neutral-900 mb-2">
            <span className="flex items-center space-x-2">
              <svg className="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
              </svg>
              <span>排除文件模式</span>
            </span>
          </label>
          <textarea
            id="excludePatterns"
            value={excludePatternsText}
            onChange={(e) => setExcludePatternsText(e.target.value)}
            rows={6}
            className="w-full px-3 py-2 border border-neutral-200 rounded-xl shadow-medium focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 hover:shadow-strong font-mono text-sm font-medium bg-white resize-none"
            placeholder="每行一个模式，支持通配符\n例如：\nnode_modules/*\n*.log\n.git/*"
          />
          <p className="text-xs text-neutral-600 mt-2 flex items-start space-x-2">
            <svg className="w-3 h-3 text-info-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>指定在分析Git变更时要排除的文件模式，每行一个模式，支持 * 和 ? 通配符</span>
          </p>
        </div>

        {/* 保存按钮 */}
        <div className="flex justify-end pt-3 border-t border-neutral-200">
          <button
            type="submit"
            disabled={saving}
            className="px-4 py-2 bg-gradient-to-r from-primary-600 to-primary-700 text-white rounded-xl hover:from-primary-700 hover:to-primary-800 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:ring-offset-1 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2 transition-all duration-300 font-semibold text-sm shadow-strong hover:shadow-stronger transform hover:scale-105"
          >
            {saving && (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
            )}
            {!saving && (
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3-3m0 0l-3 3m3-3v12" />
              </svg>
            )}
            <span>{saving ? '保存中...' : '保存配置'}</span>
          </button>
        </div>
      </form>
    </div>
  );
};